package org.example.dao;

import com.mysql.cj.Session;
import org.example.db.JDBCUtil;
import org.example.javabean.*;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class MessageDao
{
    public int insertMessage(String username,String message) {
        int result=0;
        String sql = "\n" +
                "insert INTO message VALUES(id,?,?,now())";
        try
        {
            result = JDBCUtil.getInstance().executeUpdate(sql,new Object[]{username,message});
        }
        catch (Exception e) {
            e.printStackTrace();

        }
        return result;
    }
    public List<Message> selectAllMessage(int pageNum, int pageSize) {
        String sql = "select message.*,borrow_card.reader from message,borrow_card where message.card_id=borrow_card.username limit ?,?";
        List<Message> messages = new ArrayList<>();
        try (ResultSet rs = JDBCUtil.getInstance().executeQueryRS(sql,
                new Object[]{(pageNum - 1) * pageSize, pageSize})) {
            while (rs.next()) {
                Message message = new Message(
                        rs.getString("reader"),
                        rs.getString("detail"),
                        rs.getDate("public_date"));
                messages.add(message);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return messages;
    }


    public int selectMessageCount() {
        String sql = "\n" +
                "select COUNT(*) as num from message,borrow_card where message.card_id=borrow_card.username";
        try (final ResultSet rs =
                     JDBCUtil.getInstance().executeQueryRS(sql,
                             new Object[]{})) {
            while (rs.next()) {
                return rs.getInt("num");
            }
        } catch (SQLException e) {
            e.printStackTrace();
            return 0;
        }
        return 0;
    }
}